package com.hinnotek.amoeba.ui.fragment

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import androidx.fragment.app.viewModels
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.adapters.old.HomeManagerMsgListRecyclerAdapter
import com.hinnotek.amoeba.bean.old.AllSysOrg
import com.hinnotek.amoeba.bean.old.HomeMsgListBean
import com.hinnotek.amoeba.bean.old.NoticePageByUserIdBean
import com.hinnotek.amoeba.databinding.FragmentHomeManagerMsgBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.ext.initAdapter
import com.hinnotek.amoeba.ui.activity.old.*
import com.hinnotek.amoeba.utilities.IntentUtils
import com.hinnotek.amoeba.utilities.ToastUtils
import com.hinnotek.amoeba.viewmodels.NoticeViewModel
import com.lee.common.base.BaseFragment
import com.lee.common.network.getRequestBody
import com.lee.common.network.net.ObserverState
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import com.xuexiang.xui.utils.WidgetUtils
import dagger.hilt.android.AndroidEntryPoint
import java.util.*

/**
 * 消息列表Fragment标签页
 * 2020-10-7,张洋修改
 */
@AndroidEntryPoint
class FragmentHomeManagerMsg : BaseFragment<FragmentHomeManagerMsgBinding>() {
    private var myHMLRAdapter: HomeManagerMsgListRecyclerAdapter? = null
    private val myHomeMsgListBean = HomeMsgListBean()
    private var searchId = 0
    private var pageNo = 1
    private val pageSize = 20

    val viewModel by viewModels<NoticeViewModel>()


    private val strings = arrayOf<String?>(
        "全部", "阿米巴采购申请", "阿米巴付款申请", "阿米巴报销申请", "阿米巴临时缴费续费申请",
        "阿米巴安装申请", "公司商务采购申请", "公司手机号缴费申请"
    )
    private val beans: MutableList<Bean> = ArrayList()

    override fun initView(view: View) {
        myHomeMsgListBean.data = ArrayList()

        WidgetUtils.initRecyclerView(mBinding.recyclerView3, 0)
        mBinding.recyclerView3.adapter = HomeManagerMsgListRecyclerAdapter().also {
            myHMLRAdapter = it
        }
        myHMLRAdapter!!.setOnItemClickListener { adapter, _, position ->
            val data = adapter.getItem(position) as NoticePageByUserIdBean
            val bundle = Bundle()
            bundle.putInt("noticeId", data.noticeId)
            bundle.putInt("type", 1)
            if (data.noticeTypeId == 1) { //通知类型ID1-阿米巴采购申请2-阿米巴付款申请3-阿米巴报销申请4-阿米巴临时缴费续费申请5-阿米巴安装申请6-公司商务采购申请7-公司手机号缴费申请
                IntentUtils.startActivity(
                    mContext,
                    MsgPurchaseRequisitionDetailActivity::class.java,
                    bundle
                )
            } else if (data.noticeTypeId == 2) {
                IntentUtils.startActivity(
                    mContext,
                    MsgPaymentRequestDetailActivity::class.java, bundle
                )
            } else if (data.noticeTypeId == 3) {
                IntentUtils.startActivity(mContext, MsgWipeOutDetailActivity::class.java, bundle)
            } else if (data.noticeTypeId == 4) {
                IntentUtils.startActivity(
                    mContext,
                    MsgRenewalPaymentDetailActivity::class.java, bundle
                )
            } else if (data.noticeTypeId == 5) {
                IntentUtils.startActivity(
                    mContext,
                    MsgOtherAmoebaInstalledDetailActivity::class.java, bundle
                )
            } else if (data.noticeTypeId == 6) {
                IntentUtils.startActivity(mContext, MsgPurchaseDetailActivity::class.java, bundle)
            } else if (data.noticeTypeId == 7) {
                IntentUtils.startActivity(
                    mContext,
                    MsgPhoneNumberPaymentDetailActivity::class.java, bundle
                )
            }
        }
        mBinding.superButtonSubmit.setOnClickListener { v: View? ->
            mBinding.refreshLayout3.autoRefresh() //第一次进入触发自动刷新，演示效果
        }
        //下拉刷新
        mBinding.refreshLayout3.setOnRefreshListener { refreshLayout ->
            refreshLayout.layout.postDelayed({
                pageNo = 1
                getAmibaTemporaryePageByUserId()
            }, 0)
        }
        //上拉加载
        mBinding.refreshLayout3.setOnLoadMoreListener { refreshLayout ->
            refreshLayout.layout.postDelayed({
                pageNo++
                getAmibaTemporaryePageByUserId()
            }, 0)
        }
        for (i in strings.indices) {
            beans.add(Bean(i, strings[i]!!))
        }

        mBinding.mscSearch.initAdapter(strings)

        mBinding.mscSearch.setOnItemClickListener { parent, view, position, id ->
            searchId = beans[position].id
        }
        getAllSysOrg()
        super.initView(view)
    }

    override fun initData() {


    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_home_manager_msg
    }

    override fun isVisible(isVisible: Boolean) {

        super.isVisible(isVisible)
    }

    override fun onResume() {
        mBinding.refreshLayout3.autoRefresh() //第一次进入触发自动刷新，演示效果
        super.onResume()

    }


    inner class Bean(var id: Int, var name: String)


    private fun getAllSysOrg() {

        viewModel.getAllSysOrg().observe(this, object : ObserverState<MutableList<AllSysOrg>>() {
            override fun onDataChange(data: MutableList<AllSysOrg>) {
                val stringList = mutableListOf<String>()
                stringList.add("选择公司或阿米巴");
                for (elm in data) {
                    stringList.add(elm.orgName)
                }
                mBinding.mscSearchCompanyAmoeba.initAdapter(strings)
                super.onDataChange(data)
            }

            override fun onError(msg: String?, code: Int) {
                ToastUtils.showShort(mContext, msg)
                super.onError(msg, code)
            }
        })
    }

    /**
     * app端通过申请人获取临时缴费续费申请分页接口
     */

    fun getAmibaTemporaryePageByUserId() {
        val customDialog = CustomDialog(activity, "正在加载...")
        customDialog.show()
        var orgName = mBinding.mscSearchCompanyAmoeba.editText.text.toString()
        if (orgName == "选择公司或阿米巴") {
            orgName = ""
        }
        val map = mutableMapOf<String, Any>().apply {
            put("noticeTypeId", searchId)
            put("orgName", orgName)
            put("pageNo", pageNo)
            put("pageSize", pageSize)
        }

        viewModel.getNoticePage(getRequestBody(map))
            .observe(this, object : ObserverState<MutableList<NoticePageByUserIdBean>>() {
                override fun onDataChange(data: MutableList<NoticePageByUserIdBean>) {

                    customDialog.dismiss()
                    if (pageNo == 1) {
                        when (getRefreshStatus(data.size)) {
                            Status.SUCCESS -> {
                                myHMLRAdapter!!.setList(data)
                                if (data.size < pageSize) {
                                    mBinding.refreshLayout3.setEnableLoadMore(false)
                                } else {
                                    mBinding.refreshLayout3.setEnableLoadMore(true)
                                }
                                mBinding.refreshLayout3.resetNoMoreData() //setNoMoreData(false);
                                mBinding.llStateful3.showContent()
                            }
                            Status.EMPTY -> {
                                mBinding.llStateful3.showEmpty()
                                mBinding.refreshLayout3.setEnableLoadMore(false)
                            }
                            Status.ERROR -> showError()
                            Status.NO_NET -> showOffline()

                        }
                        mBinding.refreshLayout3.finishRefresh()
                    } else {
                        if (data.size == 0) {
                            ToastUtils.showShort("数据全部加载完毕")
                            mBinding.refreshLayout3.finishLoadMoreWithNoMoreData() //将不会再次触发加载更多事件
                        } else {
                            myHMLRAdapter?.addData(data)
                            mBinding.refreshLayout3.finishLoadMore()
                        }
                    }
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    showError()
                    customDialog.dismiss()
                    ToastUtils.showShort(msg)
                    super.onError(msg, code)
                }
            })
    }

    private fun showOffline() {
        mBinding.llStateful3.showOffline { v: View? -> mBinding.refreshLayout3.autoRefresh() }
        mBinding.refreshLayout3.setEnableLoadMore(false)
    }

    private fun showError() {
        mBinding.llStateful3.showError { v: View? -> mBinding.refreshLayout3.autoRefresh() }
        mBinding.refreshLayout3.setEnableLoadMore(false)
    }

    private enum class Status {
        SUCCESS, EMPTY, ERROR, NO_NET
    }

    private fun getRefreshStatus(size: Int): Status {
        return if (size == 0) {
            Status.EMPTY
        } else Status.SUCCESS
    }
}